package com.bodacn.storagescan.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.bodacn.storagescan.DBUtil;
import com.bodacn.storagescan.MainApplication;
import com.bodacn.storagescan.R;
import com.bodacn.storagescan.ScannerManager;
import com.bodacn.storagescan.adapter.PiecelvScanAdapter;
import com.bodacn.storagescan.bean.ProcessDetailBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.bodacn.storagescan.BaseRequest.postJsonData;

/**
 * 裁剪呼叫
 */
public class NHActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_top_subject)
    TextView tvTopSubject;
    @BindView(R.id.tv_top_right)
    TextView tvTopRight;
    @BindView(R.id.ll_include)
    LinearLayout llInclude;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_songbujiahao)
    TextView tvhuojiahao;
    @BindView(R.id.tv_mianliaotiaoma)
    TextView tv_baotiaoma;
    @BindView(R.id.tv_kuweihao)
    TextView tvKuweihao;
    @BindView(R.id.tv_huojiahao)
    TextView tvHuojiahao;
    @BindView(R.id.tv_hetongaho)
    TextView tvHetongaho;
    @BindView(R.id.tv_kuanhao)
    TextView tvKuanhao;
    @BindView(R.id.tv_yanse)
    TextView tvYanse;
    @BindView(R.id.tv_chima)
    TextView tvChima;
    @BindView(R.id.tv_jianshu)
    TextView tvJianshu;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.lv_detail)
    ListView lvDetail;
    @BindView(R.id.lv_left_scrollview)
    HorizontalScrollView lvLeftScrollview;
    @BindView(R.id.tv_ResultInfo)
    TextView tvResultInfo;
    @BindView(R.id.tv_bangding)
    TextView tvBangding;
    @BindView(R.id.tv_jiebang)
    TextView tvJiebang;
    @BindView(R.id.tv_away)
    TextView tvAway;

    ScannerManager scannerManager;
    private String TAG = getClass().getSimpleName();
    String curLoginUserNo;//操作员所属部门等信息;
    String IsBind = "", PrBarcode = "";
    private final static int MSG_ERROR = 9003;
    private final static int MSG_ScanBarcodeOver = 9001;
    private final static int MSG_DETAIL = 9000;
    private final static int MSG_CallAgvResult = 9008;
    JSONArray detailJSON;
    private List<ProcessDetailBean> listlv = new ArrayList<>();
    PiecelvScanAdapter piecelvScanAdapter;

    MainApplication mApp;


//    @Override
//    public boolean dispatchKeyEvent(KeyEvent event) {
//        if (scannerManager.dispatchKeyEvent(event)) {
//            return true;
//        }
//        return super.dispatchKeyEvent(event);
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mApp = (MainApplication) getApplication();
        tvTopSubject.setText("粘合呼叫");

        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo = paramBundle.getString("LoginUserNo");

        piecelvScanAdapter = new PiecelvScanAdapter(this, listlv);
        lvDetail.setAdapter(piecelvScanAdapter);

//        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
//            @Override
//            public void onResult(String code) {
//                Log.d(TAG, "code= " + code);
//                playRingtone();
//                IsBind = "";
//                editBarcode.setText(code);
//                ScanBarcode(editBarcode.getText().toString(), "ScanBarcode");
//            }
//        });


        editBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    System.out.println("code:"+event.getKeyCode());
                    if ((event.getAction()==KeyEvent.ACTION_UP)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        ScanBarcode(editBarcode.getText().toString(),"ScanBarcode");
                        return true;
                    }
                }
                return false;
            }
        });
        editBarcode.requestFocus();
        editBarcode.requestFocusFromTouch();
    }

    private void ScanBarcode(String scanBarcode, String OperType) {
        hideIM(editBarcode);
        String SqlComm = "Exec AGV_NH_ScanBarcode @OperType='" + OperType + "' , @Barcode='" + scanBarcode + "',@FormType='" + TAG + "',"
                + "@PrBarcode='" + PrBarcode
                + "',@RackNo='" + tvhuojiahao.getText().toString()
                + "',@TXM='" + tv_baotiaoma.getText().toString()
                + "',@PlaceNo='" + tvKuweihao.getText().toString()
                + "',@IsBind='" + IsBind
                + "',@UserNo='" + curLoginUserNo
                + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println("结果--" + jsonArray);
                    System.out.println("过程--" + SQLComm);
                    //往界面转数据;
                    String OperType = "";
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (OperType.equals("ScanBarcode") == true) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ScanBarcodeOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("LoadDetail") == true) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DETAIL;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }

                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "未返回任何数据!");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                } finally {
                }

            }

        };
        new Thread(run).start();

    }

    Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            Bundle bundle = msg.getData();
            hideIM(editBarcode);
            switch (msgId) {
                case MSG_ERROR:
                    String HintInfo = bundle.getString("HintInfo");
                    tvResultInfo.setText(HintInfo);
                    break;
                case MSG_ScanBarcodeOver:
                    if (detailJSON != null) {
                        //填充屏幕
                        fillScreen(detailJSON.optJSONObject(0));
                    }
                    break;
                case MSG_DETAIL:
                    if (detailJSON != null) {
                        List<ProcessDetailBean> fabeDetailBeans = new Gson().fromJson(String.valueOf(detailJSON), new TypeToken<List<ProcessDetailBean>>() {
                        }.getType());
                        listlv.clear();
                        listlv.addAll(fabeDetailBeans);
                        piecelvScanAdapter.notifyDataSetChanged();
                        tvResultInfo.setText(listlv.get(0).getResultInfo());
                    } else {
                        listlv.clear();
                        piecelvScanAdapter.notifyDataSetChanged();
                    }
                    break;
                //呼叫出库回调
                case MSG_CallAgvResult:
                    String tmpstr = msg.obj.toString();
                    try {
                        JSONObject jsonObject = new JSONObject(tmpstr);
                        if (jsonObject.has("status") && jsonObject.has("errorinfo")) {
                            tvResultInfo.setText(jsonObject.getString("errorinfo"));
                            if (jsonObject.getInt("status") == 0)
                                tvResultInfo.setTextColor(getResources().getColor(R.color.green));
                            else
                                tvResultInfo.setTextColor(getResources().getColor(R.color.red));
                        } else {
                            tvResultInfo.setText(msg.obj.toString());
                        }
                        if (jsonObject.has("data") && jsonObject.get("data") != null) {
                            String data = jsonObject.getString("data");
                            JSONArray jsonArray = new JSONArray(data);
                            /*jsonArray包含OperType,ReqCode,StartPlace,EndPlace,RowIndex,TaskCode,message,可以选择显示*/
                            if (jsonArray != null && jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject object = jsonArray.getJSONObject(i);
                                    if (object.has("TaskCode") && object.has("message")) {
                                        tvResultInfo.setText(tvResultInfo.getText().toString() + "\r\n" + object.getString("TaskCode") + ":" + object.getString("message")
                                        );
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;
            }
        }
    };


    private void fillScreen(JSONObject optJSONObject) {
        if (optJSONObject != null) {
            try {
                if (optJSONObject.has("RackNo"))
                    tvhuojiahao.setText(optJSONObject.getString("RackNo"));
                if (optJSONObject.has("TXM"))
                    tv_baotiaoma.setText(optJSONObject.getString("TXM"));
                if (optJSONObject.has("PlaceNo")) {
                    tvKuweihao.setText(optJSONObject.getString("PlaceNo"));
                }
                if (optJSONObject.has("ResultInfo"))
                    tvResultInfo.setText(optJSONObject.getString("ResultInfo"));
                if (optJSONObject.has("LoadDetail")) {
                    if (optJSONObject.getString("LoadDetail").equals("Y")) {
                        ScanBarcode(editBarcode.getText().toString(), "LoadDetail");
                    } else {
                        listlv.clear();
                        piecelvScanAdapter.notifyDataSetChanged();
                    }
                }
                if (optJSONObject.has("ErrInfo") == true) {
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(optJSONObject.getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(editBarcode);
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_nh;
    }

    @OnClick({R.id.tv_pull,R.id.iv_back, R.id.tv_sure, R.id.tv_bangding, R.id.tv_jiebang, R.id.tv_away})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_sure:
                ScanBarcode(editBarcode.getText().toString(), "ScanBarcode");
                break;
            case R.id.tv_bangding:
                IsBind = "绑定";
                ScanBarcode(editBarcode.getText().toString(), "ScanBarcode");
                break;
            case R.id.tv_jiebang:
                IsBind = "解绑";
                ScanBarcode(editBarcode.getText().toString(), "ScanBarcode");
                break;
            case R.id.tv_away:
                if (!TextUtils.isEmpty(mApp.AgvUrl)) {
                    PutAGVTask("搬走满货架");
                } else {
                    Toast.makeText(NHActivity.this, "请先设置Agv地址", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_pull:
                if (!TextUtils.isEmpty(mApp.AgvUrl)) {
                    PutAGVTask("搬来空货架");
                } else {
                    Toast.makeText(NHActivity.this, "请先设置Agv地址", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    //调用Agv通用接口
    private void PutAGVTask(String OperType) {
        String SqlComm = "Exec AGV_Cut_ScanBarcode @OperType='" + OperType + "' , @Barcode='" + editBarcode.getText().toString() + "',@FormType='" + TAG + "',"
                + "@PrBarcode='" + PrBarcode
                + "',@RackNo='" + tvhuojiahao.getText().toString()
                + "',@TXM='" + tv_baotiaoma.getText().toString()
                + "',@PlaceNo='" + tvKuweihao.getText().toString()
                + "',@IsBind='" + IsBind
                + "',@UserNo='" + curLoginUserNo
                + "'";
        /*Sql由接口执行，返回数据集字段OperType,ReqCode,StartPlace,EndPlace,RowIndex*/
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("sqlComm", SqlComm);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("PutAGVTask请求:" + MainApplication.AgvUrl + "/api/hikAgv/callAgv");
        System.out.println("PutAGVTask参数:" + jsonObject.toString());
        //直接调用呼叫接口;
        postJsonData(MainApplication.AgvUrl + "/api/hikAgv/callAgv", jsonObject.toString(), handler, MSG_CallAgvResult);
    }
}
